/**
 * 消息处理器 - 用于处理来自WebSocket或其他源的消息
 * 可在主应用和浏览器插件中复用
 */

class MessageProcessor {
    constructor() {
        // 初始化消息处理器
        this.messageHandler = new MessageHandler();
        
        // 存储WebSocket连接
        this.websocket = null;
        
        // 重连相关配置
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000;
    }
    
    /**
     * 连接到WebSocket服务器
     * @param {string} url - WebSocket服务器地址
     */
    connectWebSocket(url) {
        try {
            this.websocket = new WebSocket(url);
            
            // 绑定事件处理器
            this.websocket.onopen = (event) => this.onWebSocketOpen(event);
            this.websocket.onmessage = (event) => this.onWebSocketMessage(event);
            this.websocket.onclose = (event) => this.onWebSocketClose(event);
            this.websocket.onerror = (event) => this.onWebSocketError(event);
        } catch (error) {
            console.error('Failed to create WebSocket connection:', error);
        }
    }
    
    /**
     * WebSocket连接打开事件
     */
    onWebSocketOpen(event) {
        console.log('WebSocket connection opened:', event);
        this.reconnectAttempts = 0; // 重置重连次数
    }
    
    /**
     * 接收WebSocket消息
     */
    async onWebSocketMessage(event) {
        try {
            // 解析消息
            const message = JSON.parse(event.data);
            console.log('Received message:', message);
            
            // 处理消息
            await this.messageHandler.handleMessage(message);
        } catch (error) {
            console.error('Error parsing WebSocket message:', error);
        }
    }
    
    /**
     * WebSocket连接关闭事件
     */
    onWebSocketClose(event) {
        console.log('WebSocket connection closed:', event);
        
        // 如果不是正常关闭且还有重连次数，则尝试重连
        if (!event.wasClean && this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                // 这里需要知道原来的URL才能重连
                // 在实际使用中，你需要保存原始的URL
                console.log('Reconnect logic would go here');
            }, this.reconnectDelay * this.reconnectAttempts); // 指数退避
        }
    }
    
    /**
     * WebSocket错误事件
     */
    onWebSocketError(event) {
        console.error('WebSocket error:', event);
    }
    
    /**
     * 发送消息到WebSocket服务器
     * @param {Object} message - 要发送的消息
     */
    sendMessage(message) {
        if (this.websocket && this.websocket.readyState === WebSocket.OPEN) {
            this.websocket.send(JSON.stringify(message));
        } else {
            console.warn('WebSocket is not connected. Cannot send message.');
        }
    }
    
    /**
     * 断开WebSocket连接
     */
    disconnectWebSocket() {
        if (this.websocket) {
            this.websocket.close();
            this.websocket = null;
        }
    }
    
    /**
     * 注册自定义消息处理函数
     * @param {string} messageType - 消息类型
     * @param {Function} handler - 处理函数
     */
    registerHandler(messageType, handler) {
        this.messageHandler.registerHandler(messageType, handler);
    }
    
    /**
     * 处理直接传入的消息（非WebSocket）
     * @param {Object|string} message - 消息内容
     */
    async processDirectMessage(message) {
        let parsedMessage;
        
        if (typeof message === 'string') {
            try {
                parsedMessage = JSON.parse(message);
            } catch (error) {
                console.error('Invalid JSON message:', error);
                return;
            }
        } else {
            parsedMessage = message;
        }
        
        await this.messageHandler.handleMessage(parsedMessage);
    }
}

// 初始化默认的消息处理函数
MessageProcessor.prototype.initDefaultHandlers = function() {
    // 页面刷新
    this.registerHandler('REFRESH_PAGE', () => {
        window.location.reload();
    });
    
    // 新标签页打开URL
    this.registerHandler('OPEN_URL_IN_NEW_TAB', (data) => {
        const { url } = data;
        if (url) {
            window.open(url, '_blank');
        }
    });
    
    // 刷新缓存
    this.registerHandler('REFRESH_CACHE', () => {
        // 清除localStorage
        localStorage.clear();
        // 清除sessionStorage
        sessionStorage.clear();
        console.log('Cache cleared');
    });
    
    // 显示通知
    this.registerHandler('SHOW_NOTIFICATION', async (data) => {
        const { title, message, timeout = 3000 } = data;
        
        // 在浏览器环境中使用Notification API
        if ('Notification' in window) {
            // 请求权限（如果需要）
            if (Notification.permission === 'default') {
                await Notification.requestPermission();
            }
            
            if (Notification.permission === 'granted') {
                const notification = new Notification(title, { body: message });
                setTimeout(() => notification.close(), timeout);
                return;
            }
        }
        
        // 回退到console输出
        console.log(`Notification: ${title} - ${message}`);
    });
    
    // 更新页面内容
    this.registerHandler('UPDATE_CONTENT', (data) => {
        const { selector, content, action = 'innerHTML' } = data;
        const element = document.querySelector(selector);
        if (element) {
            element[action] = content;
        }
    });
    
    // 执行JavaScript代码
    this.registerHandler('EXECUTE_SCRIPT', (data) => {
        const { script } = data;
        if (script) {
            try {
                // 注意：eval可能存在安全风险，在生产环境中应该使用更安全的方式
                eval(script);
            } catch (error) {
                console.error('Error executing script:', error);
            }
        }
    });
    
    // 修改页面样式
    this.registerHandler('MODIFY_STYLE', (data) => {
        const { selector, property, value } = data;
        const element = document.querySelector(selector);
        if (element) {
            element.style[property] = value;
        }
    });
};

// 导出类（如果在Node.js环境中）
if (typeof module !== 'undefined' && module.exports) {
    module.exports = MessageProcessor;
} else {
    // 在浏览器环境中，将类添加到全局作用域
    window.MessageProcessor = MessageProcessor;
}